import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';

import '../entity/product_entity.dart';
import '../entity/store_detail_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/common_utils.dart';

///
/// 店铺主页的第一分页
///
class MallHomeIndexPage extends StatefulWidget {
  var storeId = '';

  MallHomeIndexPage({Key? key, this.storeId = ''}) : super(key: key);

  @override
  State<MallHomeIndexPage> createState() => _MallHomeIndexPageState();
}

class _MallHomeIndexPageState extends State<MallHomeIndexPage> {
  StoreDetailEntity entity = StoreDetailEntity();
  List<ProductData> datas = [];
  var page = 1;

  getProducts() async {
    var param = {
      'page': page.toString(),
      'size': '20',
      'order_by': 'sales',
      'sort': 'desc',
      'store_id': widget.storeId
    };
    dynamic result = await Api.goodsList(param);
    ProductEntity entity = ProductEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  getData() async {
    dynamic result = await Api.storeDetail(widget.storeId);
    setState(() {
      entity = StoreDetailEntity.fromJson(result);
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
    getProducts();
  }

  //返回商品列表item
  getListItem(int index) {
    return Container(
      height: 180.w,
      margin: EdgeInsets.symmetric(horizontal: 5.w, vertical: 0.w),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Config.colorDivider, width: 2.w),
        ),
      ),
      child: InkWell(
        onTap: () {
          Routes.navigateTo(context, Routes.productDetail, params: {'productId': datas[index].id});
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(left: 20.w, right: 20.w),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(5),
                child: CachedNetworkImage(
                  imageUrl: CommonUtils.compressImageUrl(datas[index].mainImg, 200, 200),
                  fit: BoxFit.fill,
                  width: 140.w,
                  height: 140.w,
                  errorWidget: (context, url, error) {
                    return Image.asset(
                      'assets/images/bg_default_400.png',
                      width: 140.w,
                      height: 140.w,
                      fit: BoxFit.fill,
                    );
                  },
                ),
              ),
            ),
            Container(
              height: 140.w,
              width: 480.w,
              child: Stack(
                children: [
                  Text(
                    datas[index].name,
                    softWrap: true,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: (Config.colorText1), fontSize: 22.w),
                  ),
                  Positioned(
                    bottom: 32.w,
                    child: Text(
                      "已售 ${datas[index].salesNum}",
                      style: TextStyle(fontSize: 20.sp, color: Config.colorText1),
                    ),
                  ),
                  Positioned(
                    bottom: 0.w,
                    child: Text(
                      CommonUtils.formatAmountUnit(datas[index].money, datas[index].company,
                          datas[index].money1, datas[index].company1),
                      style: TextStyle(fontSize: 20.sp, color: Colors.red),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(12.w),
        ),
        child: EasyRefresh.builder(
          header: const MaterialHeader(),
          footer: const MaterialFooter(),
          onRefresh: () async {
            await Future.delayed(const Duration(milliseconds: 200), () {
              page = 1;
              getProducts();
            });
          },
          onLoad: () async {
            getProducts();
          },
          childBuilder: (context, physics) {
            return ListView(
              scrollDirection: Axis.vertical,
              physics: physics,
              children: [
                SizedBox(
                  //轮播
                  height: 240.w,
                  child: Swiper(
                    itemBuilder: (BuildContext context, int index) {
                      return ClipRRect(
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(12.w),
                          topRight: Radius.circular(12.w),
                        ),
                        child: CachedNetworkImage(
                          imageUrl:
                              CommonUtils.compressImageUrl(entity.data.banner[index], 700, 240),
                          fit: BoxFit.fill,
                          width: double.infinity,
                          height: double.infinity,
                          errorWidget: (context, url, error) {
                            return Image.asset(
                              'assets/images/bg_default_400.png',
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.fill,
                            );
                          },
                        ),
                      );
                    },
                    onTap: (index) {},
                    autoplayDelay: 4000,
                    autoplay: true,
                    loop: false,
                    layout: SwiperLayout.DEFAULT,
                    itemCount: entity.code == 1 ? entity.data.banner.length : 0,
                    // viewportFraction: 0.7,
                    // scale: 0.8,
                    pagination: SwiperPagination(
                      builder: DotSwiperPaginationBuilder(
                          // size: Size(20.w, 4.w),
                          // activeSize: Size(20.w, 4.w),
                          size: 15.w,
                          activeSize: 15.w,
                          activeColor: Config.colorMain,
                          color: Config.colorWhite),
                    ),
                  ),
                ),
                Container(
                  height: 80.w,
                  margin: EdgeInsets.only(top: 0.w),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(color: Config.colorDivider, width: 2.w),
                    ),
                  ),
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      InkWell(
                        onTap: () {},
                        child: Text(
                          '热卖专区',
                          style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                        ),
                      ),
                    ],
                  ),
                ),
                Column(
                  children: [
                    ListView.builder(
                      itemCount: datas.length,
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return getListItem(index);
                      },
                    ),
                  ],
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
